<template>
  <div class="role-view">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="角色名">
          <el-input
            v-model="searchForm.roleName"
            placeholder="请输入要搜索的角色名"
            maxlength="16"
            show-word-limit
            clearable
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 角色列表 -->
    <card>
      <!-- 列表上方的操作按钮 -->
      <div class="table-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button 
          type="danger" 
          :disabled="selectedRoles.length === 0"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          删除
        </el-button>
      </div>
      <element-table
        :data="roles"
        :table-title="tableConfig"
        :del-method="deleteRole"
        :refresh-method="loadRoles"
        :del-params="getDelParams"
        :item-type="'角色'"
        :show-pagination="false"
        @select-change="handleSelectionChange"
      />
    </card>

    <!-- 角色编辑对话框 -->
    <RoleDialog
      v-model="roleDialogVisible"
      :role-data="currentRoleData"
      @success="handleDialogSuccess"
    />

    <!-- 权限设置抽屉 -->
    <RolePermissionsDrawer
      v-model:visible="permissionsDrawerVisible"
      :role-data="currentPermissionsRole"
      @success="handlePermissionsSuccess"
    />

    <!-- 用户列表对话框 -->
    <UserListDialog
      v-model:visible="userListDialogVisible"
      :role-id="currentRoleForUsers?.roleId"
      :role-name="currentRoleForUsers?.roleName"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus, Search, Refresh, Delete } from '@element-plus/icons-vue'
import { api } from '@/api'
import { confirm } from '@/utils/confirm'
import { success, error, warning } from '@/utils/toast'
import card from '@/components/card/index.vue'
import elementTable from '@/components/ElementTable/index.vue'
import RoleDialog from './components/RoleDialog.vue'
import RolePermissionsDrawer from './components/RolePermissionsDrawer.vue'
import UserListDialog from '@/components/UserListDialog.vue'

// 响应式数据
const roles = ref<any[]>([])
const originalRoles = ref<any[]>([]) // 存储原始角色数据，用于本地筛选
const selectedRoles = ref<any[]>([])
const loading = ref(false)

// 对话框相关
const roleDialogVisible = ref(false)
const currentRoleData = ref<any>(null)

// 权限设置抽屉相关
const permissionsDrawerVisible = ref(false)
const currentPermissionsRole = ref<any>(null)

// 用户列表对话框相关
const userListDialogVisible = ref(false)
const currentRoleForUsers = ref<any>(null)

// 注意：已移除分页配置，现在显示所有角色

// 搜索表单
const searchForm = reactive({
  roleName: ''
})

// 表格配置
const tableConfig = ref([
  {
    type: 'selection',
    width: '50',
    fn: (row: any) => row.roleId !== 1 // roleId为1的角色不能被选中
  },
  {
    type: 'text',
    label: '角色名',
    prop: 'roleName',
  },
  {
    type: 'operate',
    label: '操作',
    actions: [
      {
        name: '设置权限',
        type: 'primary',
        size: 'small',
        isLink: true,
        click: (row: any) => handleSetPermissions(row),
        show: (row: any) => row.roleId !== 1  // 当roleId为1时隐藏
      },
      {
        name: '修改',
        type: 'primary',
        size: 'small',
        isLink: true,
        click: (row: any) => handleEdit(row),
        show: (row: any) => row.roleId !== 1  // 当roleId为1时隐藏
      },
      {
        name: '删除',
        type: 'danger',
        size: 'small',
        isLink: true,
        click: (row: any) => handleDelete(row),
        showDel: (row: any) => row.roleId !== 1 // roleId为1的角色不显示删除按钮
      },
      {
        name: '查看用户',
        type: 'primary',
        size: 'small',
        isLink: true,
        click: (row: any) => handleViewUsers(row)
      }
    ]
  }
])

// 加载角色列表
const loadRoles = async () => {
  try {
    loading.value = true
    const response = await api.role.getAllRoles()
    const allRoles = response.data || []
    
    // 保存原始数据
    originalRoles.value = allRoles
    
    // 应用搜索筛选
    applySearchFilter()
  } finally {
    loading.value = false
  }
}

// 应用搜索筛选
const applySearchFilter = () => {
  let filteredRoles = originalRoles.value
  
  // 如果有搜索关键词，进行本地筛选
  if (searchForm.roleName.trim()) {
    const searchText = searchForm.roleName.toLowerCase()
    filteredRoles = originalRoles.value.filter(role => 
      role.roleName?.toLowerCase().includes(searchText)
    )
  }
  
  // 直接显示所有筛选后的角色，不分页
  roles.value = filteredRoles
}

// 搜索功能
const handleSearch = () => {
  // 直接应用搜索筛选，不需要重新加载数据
  applySearchFilter()
}

// 重置搜索
const handleReset = () => {
  searchForm.roleName = ''
  // 直接应用搜索筛选，不需要重新加载数据
  applySearchFilter()
}

// 新增角色
const handleAdd = () => {
  currentRoleData.value = null
  roleDialogVisible.value = true
}

// 编辑角色
const handleEdit = (row: any) => {
  currentRoleData.value = row
  roleDialogVisible.value = true
}

// 设置权限
const handleSetPermissions = (row: any) => {
  currentPermissionsRole.value = row
  permissionsDrawerVisible.value = true
}

// 删除单个角色
const handleDelete = async (row: any) => {
  try {
    await confirm.delete(row.roleName, '角色')
    
    await api.role.deleteRole(row.id)
    success('删除成功')
    loadRoles()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('删除角色失败:', err)
      error('删除角色失败')
    }
  }
}

// 获取删除参数
const getDelParams = (row: any) => {
  return {
    id: row.roleId,
    name: row.roleName
  }
}

// 删除角色方法（供elementTable组件调用）
const deleteRole = async (param: any) => {
  try {
    // 兼容处理，支持传入id或包含id的对象
    const roleId = typeof param === 'object' ? param.id : param
    await api.role.deleteRole(roleId)
    success('删除成功')
    // 从原始数据中移除删除的角色
    originalRoles.value = originalRoles.value.filter(role => role.id !== roleId)
    // 重新应用搜索筛选
    applySearchFilter()
    return true
  } catch (err) {
    console.error('删除角色失败:', err)
    return false
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRoles.value.length === 0) {
    warning('请选择要删除的角色')
    return
  }

  try {
    await confirm.batch('删除', selectedRoles.value.length, '角色')
    
    const ids = selectedRoles.value.map((role: any) => role.roleId)
    let successCount = 0
    let failCount = 0
    
    // 逐个调用删除接口
    for (const id of ids) {
      try {
        await api.role.deleteRole(id)
        successCount++
      } catch (err) {
        console.error(`删除角色ID ${id} 失败:`, err)
        failCount++
      }
    }
    
    if (failCount === 0) {
      success(`批量删除成功，共删除 ${successCount} 个角色`)
    } else if (successCount === 0) {
      error('批量删除失败')
    } else {
      warning(`批量删除完成，成功 ${successCount} 个，失败 ${failCount} 个`)
    }
    
    // 从原始数据中移除删除的角色
    originalRoles.value = originalRoles.value.filter(role => !ids.includes(role.roleId))
    // 重新应用搜索筛选
    applySearchFilter()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('批量删除失败:', err)
      error('批量删除失败')
    }
  }
}

// 选择变化处理
const handleSelectionChange = (selection: any[]) => {
  selectedRoles.value = selection
}

// 对话框成功回调
const handleDialogSuccess = () => {
  // 重新加载数据以获取最新信息
  loadRoles()
}

// 权限设置成功回调
const handlePermissionsSuccess = () => {
  // 重新加载数据以获取最新信息
  loadRoles()
}

// 查看用户
const handleViewUsers = (row: any) => {
  currentRoleForUsers.value = row
  userListDialogVisible.value = true
}

// 组件挂载时加载数据
onMounted(() => {
  loadRoles()
})
</script>

<style scoped>
.role-view {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}


.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  padding: 0 4px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}
</style>